package com.atguigu.gulimallssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author houChen
 * @date 2022/1/1 15:36
 * @Description:
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        String userName = redisTemplate.opsForValue().get(token);
        return userName;
    }

    @GetMapping("login.html")
    public String loginPaget(@RequestParam("redirect_url") String redirect_url, Model model,
                             @CookieValue(value = "sso_token",required = false) String sso_token){
        if(!StringUtils.isEmpty(sso_token)){   //说明之前用户用其他的系统登陆过sso服务器
            return "redirect:" + redirect_url + "?token=" + sso_token;
        }
        model.addAttribute("url",redirect_url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(String username,
                          String password,
                          String url,
                          HttpServletResponse response){
        if(!StringUtils.isEmpty(username)&& !StringUtils.isEmpty(password)){
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid,username);
            Cookie sso_token = new Cookie("sso_token", uuid);  //给浏览器添加一个cookie
            response.addCookie(sso_token);
            //登录工程进行跳转，跳回到之前的页面
            return "redirect:"+url + "?token=" + uuid;
        }else{
            return "login";
        }
    }

}